package com.zjlanyun.eplus;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.utils.ToastUtils;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.SPData;
import com.zjlanyun.eplus.utils.StringUtils;
import com.zjlanyun.eplus.utils.Toastor;

import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class Common {

    /**
     * 设备解绑
     *
     * @param context
     */
    public static void deviceUnbind(Context context) {
        HttpRequest httpRequest = new HttpRequest(context, SPData.getConfig().getString("device_unbind_url", ""));
        if (!SPData.getUserinfo().getBoolean("isBind", false)) {
            ToastUtils.showShortToast("设备没有绑定，请先绑定");
            return;
        }
        httpRequest.getRequest().add("device_token", SPData.getUserinfo().getString("device_token", ""));
        httpRequest.getRequest().add("customer_number", SPData.getUserinfo().getString("customer_number", ""));
        httpRequest.getRequest().add("device_type", "android");
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                SPData.getUserinfo().putBoolean("isBind", false);
                ToastUtils.showShortToast("解绑成功");
            }

            @Override
            public void onFailed(int what, Response<JSONObject> response) {
                super.onFailed(what, response);
                ToastUtils.showShortToast("解绑失败");
            }
        });
    }

    public static String formatDate(String str) {
        final String time = str.substring(6, 19).trim();
        final Date date = new Date(Long.parseLong(time));
        final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return String.valueOf(format.format(date));
    }

    // 像素倍数计算
    public static int dp2px(int dp, Context mContext) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                mContext.getResources().getDisplayMetrics());
    }

    // 获取屏幕宽度
    public static int getScrrenWidth(Context mContext) {
        Resources resources = mContext.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        return dm.widthPixels;
    }

    // 获取屏幕高度
    public static int getScreenHeight(Context mContext) {
        Resources resources = mContext.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        return dm.heightPixels;
    }

    public static String subString(String str, int num) {
        if (str.length() > num) {
            str = str.substring(0, 6) + "...";
        }
        return str;
    }

    public static void showBarChart(Context context, BarChart chart, ArrayList<HashMap<String, Object>> dataList) {
        showBarChart(context, chart, dataList, -25f, 15f, 0, true, true);
    }

    /**
     * 显示柱状图
     *
     * @param context
     * @param chart
     * @param dataList
     * @param xLabelRotationAngle
     * @param extraBottomOffset
     * @param yLabelCount
     * @param isShowTip
     * @param isSubString
     */
    public static void showBarChart(Context context, BarChart chart, ArrayList<HashMap<String, Object>> dataList, float xLabelRotationAngle, float extraBottomOffset, int yLabelCount, final boolean isShowTip, boolean isSubString) {
        final Toastor toastor = new Toastor();

        final ArrayList<String> tips = new ArrayList<String>();
        ArrayList<String> xVals = new ArrayList<String>();
        ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();
        float yMin = 0;
        for (int i = 0; i < dataList.size(); i++) {
            HashMap<String, Object> item = dataList.get(i);
            if (isSubString) {
                xVals.add(Common.subString((String) item.get("name"), 6));
            } else {
                xVals.add((String) item.get("name"));
            }
            tips.add(item.get("name") + ":" + item.get("value"));
            float value = Float.parseFloat(String.valueOf(item.get("value")));
            yVals.add(new BarEntry(value, i));
            //y轴最小值
            if (value < yMin)
                yMin = value;
        }

        chart.setDrawBarShadow(false);
        //chart.setDrawValueAboveBar(true); //柱子上面显示的值的位置
        chart.setDescription("");
        chart.setMaxVisibleValueCount(60);
        chart.setPinchZoom(false);
        chart.setDrawGridBackground(false);
        chart.setScaleEnabled(false);
        chart.setExtraBottomOffset(extraBottomOffset);
        //chart.animateY(2000); //柱子动画

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelRotationAngle(xLabelRotationAngle);
        xAxis.setLabelsToSkip(0);

        YAxis leftAxis = chart.getAxisLeft();
        if (yLabelCount > 0) leftAxis.setLabelCount(yLabelCount, true); //Y轴刻度显示个数
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinValue(yMin); //设置Y轴最小值

        chart.getAxisRight().setEnabled(false);
        chart.getLegend().setEnabled(false);

        BarDataSet set1;

        //第一次初始化配置，并渲染
        set1 = new BarDataSet(yVals, "DataSet");
        set1.setBarSpacePercent(35f);
        //set1.setColors(ColorTemplate.MATERIAL_COLORS); //多色
        set1.setColor(ContextCompat.getColor(context, R.color.color_blue));
        set1.setDrawValues(false); //柱子上面不显示值

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(xVals, dataSets);
        data.setValueTextSize(10f);

        chart.setData(data);

        chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                if (isShowTip)
                    toastor.showShortToast(tips.get(h.getXIndex()));
            }

            @Override
            public void onNothingSelected() {
            }
        });
    }

    // 折线图
    public static XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
        setRenderer(renderer, colors, styles);
        return renderer;
    }

    public static void setLineChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
                                            String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor,
                                            Context context) {
        renderer.setChartTitle(title);
        renderer.setXTitle(xTitle);
        renderer.setYTitle(yTitle);
        renderer.setXAxisMin(xMin);
        renderer.setXAxisMax(xMax);
        renderer.setYAxisMin(yMin);
        renderer.setYAxisMax(yMax);
        renderer.setAxesColor(axesColor);
        renderer.setLabelsColor(labelsColor);
        renderer.setXLabelsColor(labelsColor);
        renderer.setYLabelsColor(0, labelsColor);
        renderer.setLabelsTextSize(Common.dp2px(12, context)); // 设置轴上文字大小
        renderer.setBackgroundColor(Color.WHITE);
        renderer.setMarginsColor(Color.WHITE);
        renderer.setXLabels(12); // 设置x轴刻度
        renderer.setYLabels(10); // 设置y轴刻度
        renderer.setShowGrid(true); // 是否显示表格
        renderer.setXLabelsAlign(Align.RIGHT); // X轴文字显示方向
        renderer.setYLabelsAlign(Align.RIGHT); // Y轴文字显示方向
        renderer.setZoomButtonsVisible(false); // 是否显示缩放按钮
        renderer.setZoomEnabled(false); // 是否允许缩放
        renderer.setPanEnabled(false); // 是否允许拖动
        // renderer.setPanLimits(new double[] { -10, 20, -10, 40 });
        // renderer.setZoomLimits(new double[] { -10, 20, -10, 40 });
        renderer.setAxisTitleTextSize(Common.dp2px(12, context)); // 坐标轴上标题文字大小
        renderer.setChartTitleTextSize(20);
        renderer.setLegendTextSize(Common.dp2px(12, context)); // 标注文字大小
        renderer.setPointSize(10f);
        int left = Common.dp2px(60, context);
        int bottom = Common.dp2px(40, context);
        int height = Common.dp2px(20, context);
        renderer.setMargins(new int[]{0, left, bottom, 0});
        renderer.setLegendHeight(height);
        renderer.setGridColor(Color.GRAY);
    }

    public static void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
        int length = colors.length;
        for (int i = 0; i < length; i++) {
            XYSeriesRenderer r = new XYSeriesRenderer();
            r.setColor(colors[i]);
            r.setPointStyle(styles[i]);
            renderer.addSeriesRenderer(r);
        }
    }

    public static XYMultipleSeriesDataset buildDataset(String[] titles, List<double[]> xValues,
                                                       List<double[]> yValues) {
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        addXYSeries(dataset, titles, xValues, yValues, 0);
        return dataset;
    }

    public static void addXYSeries(XYMultipleSeriesDataset dataset, String[] titles, List<double[]> xValues,
                                   List<double[]> yValues, int scale) {
        int length = titles.length;
        for (int i = 0; i < length; i++) {
            XYSeries series = new XYSeries(titles[i], scale);
            double[] xV = xValues.get(i);
            double[] yV = yValues.get(i);
            int seriesLength = xV.length;
            for (int k = 0; k < seriesLength; k++) {
                series.add(xV[k], yV[k]);
            }
            dataset.addSeries(series);
        }
    }


    /**
     * deviceID的组成为：渠道标志+识别符来源标志+hash后的终端识别符
     * <p>
     * 识别符来源标志：
     * 1， wifi mac地址（wifi）；
     * 2， IMEI（imei）；
     * 3， 序列号（sn）；
     * 4， id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        try {
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!imei.isEmpty()) {
                deviceId.append(imei);
                return deviceId.toString();
            }

            //wifi mac地址
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String wifiMac = info.getMacAddress();
            if (!wifiMac.isEmpty()) {
                deviceId.append(wifiMac);
                return deviceId.toString();
            }

            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!sn.isEmpty()) {
                deviceId.append(sn);
                return deviceId.toString();
            }

            //如果上面都没有，则生成一个id：随机码
            String uuid = UUID.randomUUID().toString();
            if (!uuid.isEmpty()) {
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append(UUID.randomUUID().toString());
        }
        return deviceId.toString();
    }

    /**
     * 检查device_token是否生成
     *
     * @param context
     */
    public static void checkDeviceToken(Context context) {
        if (SPData.getUserinfo().getString("device_token", "").equals("")) {
            String token = StringUtils.md5(getDeviceId(context));
            SPData.getUserinfo().putString("device_token", token);
        }
    }

    /**
     * 给弹出的dialog显示软键盘
     *
     * @param alertDialog
     */
    public static void showSoftInput(AlertDialog alertDialog) {
        Window window = alertDialog.getWindow();
        //window.setContentView(R.layout.in_warehouse_add_list_item);
        WindowManager.LayoutParams wparams = window.getAttributes();
        wparams.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉
        wparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        wparams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;//显示dialog的时候,就显示软键盘
        wparams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;//就是这个属性导致不能获取焦点,默认的是FLAG_NOT_FOCUSABLE,故名思义不能获取输入焦点
        window.setAttributes(wparams);
    }
}
